package services

import (
	"encoding/xml"
	"fmt"
	"github.com/jinzhu/gorm"
	"go_motor_catalog/dao"
	"io/ioutil"
	"strings"
)

const motorradPdfBaseUrl = "https://manuals.bmw-motorrad.com/manuals/BA-Extern/IN/BA-INTERNET-COM/PDF/"

type BmwMotorrad struct {
}

type NavigationMotorrad struct {
	XMLNAME xml.Name        `xml:"NAVIGATION"`
	Mrs     []NavmrMotorrad `xml:"NAV-MR"`
}

type NavmrMotorrad struct {
	XMLNAME xml.Name         `xml:"NAV-MR"`
	MrName  string           `xml:"NAME"`
	Grps    []NavGrpMotorrad `xml:"NAV-GRP"`
}

type NavGrpMotorrad struct {
	XMLNAME xml.Name           `xml:"NAV-GRP"`
	GrpName string             `xml:"NAME"`
	Models  []NavModelMotorrad `xml:"NAV-MODELL"`
}

type NavModelMotorrad struct {
	XMLNAME   xml.Name          `xml:"NAV-MODELL"`
	Type      string            `xml:"TYPSCHL,attr"`
	ModelName string            `xml:"NAME"`
	Jahrs     []NavJahrMotorrad `xml:"MODELLJAHR"`
}

type NavJahrMotorrad struct {
	XMLNAME  xml.Name        `xml:"MODELLJAHR"`
	JahrName string          `xml:"NAME"`
	Bas      []NavBaMotorrad `xml:"BA-SPRACHE"`
}

type NavBaMotorrad struct {
	XMLNAME  xml.Name `xml:"BA-SPRACHE"`
	LangUage string   `xml:"LANGUAGE,attr"`
	FileName string   `xml:"FILENAME,attr"`
}

type CatalogResMotorrad struct {
	Model    string
	Year     string
	PartName string
	Url      string
}

func NewBmwOm() *BmwMotorrad {
	return &BmwMotorrad{}
}

func (b *BmwMotorrad) getXml() *NavigationMotorrad {
	//response := util.NewHttpUtil().Get(xmlUrl)
	//body := response.Body()
	//body, ioErr := ioutil.ReadFile("/Users/duanxu/Downloads/MotorradNav.xml")
	body, ioErr := ioutil.ReadFile("E://moto/Nav.xml")
	if ioErr != nil {
		fmt.Println("xml file read error", ioErr)
		return nil
	}
	dom := &NavigationMotorrad{}
	err := xml.Unmarshal(body, dom)
	if err != nil {
		fmt.Println(err)
		return nil
	}
	return dom
}

func (b *BmwMotorrad) getPdfs() []*CatalogResMotorrad {
	res := make([]*CatalogResMotorrad, 0)
	dom := b.getXml()
	if dom == nil {
		fmt.Println("get xml or parser xml error")
		return res
	}
	for i := range dom.Mrs {
		navmr := dom.Mrs[i]
		for j := range navmr.Grps {
			//系列
			grp := navmr.Grps[j]
			for m := range grp.Models {
				//型号
				model := grp.Models[m]
				//型号名称
				name := model.ModelName
				for h := range model.Jahrs {
					jahr := model.Jahrs[h]
					//部件名称
					jahrName := jahr.JahrName
					for b := range jahr.Bas {
						ba := jahr.Bas[b]
						uage := ba.LangUage
						if uage == "01" {
							split := strings.Split(jahrName, "/")
							year := strings.Split(split[len(split)-1], " ")[0]
							pdfUrl := motorradPdfBaseUrl + ba.FileName
							res = append(res, &CatalogResMotorrad{
								Model:    name,
								Year:     year,
								PartName: jahrName,
								Url:      pdfUrl,
							})
						}
					}
				}
			}
		}
	}
	return res
}

func (b *BmwMotorrad) CrawBmwCatalogOm(db *gorm.DB) {
	pdfs := b.getPdfs()
	if len(pdfs) > 0 {
		modelOmDao := dao.NewManualModelOmDao(db)
		catalogOmDao := dao.NewManualCatalogOmDao(db)
		for i := range pdfs {
			param := pdfs[i]
			modelParam := &dao.ManualModelOm{
				ModelName: param.Model,
				ModelYear: param.Year,
				BrandId:   5,
			}
			catalogParam := &dao.ManualCatalogOm{
				CatalogUrl:  param.Url,
				CatalogDesc: param.PartName,
			}
			modelId := modelOmDao.CreateManualModelOm(modelParam)
			catalogParam.ModelId = modelId
			catalogOmDao.CreateManualCatalogOm(catalogParam)
		}
	}
}
